package com.dg11185.nearshop.activity.home;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.android.nearshop.R;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.network.http.client.HttpRequest.ActionListener;
import com.dg11185.libs.utils.netstate.NetWorkUtils;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.activity.shop.ShopDetailActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.Utils;
import com.dg11185.nearshop.net.CacheConstant;
import com.dg11185.nearshop.net.NetCacheClient;
import com.dg11185.nearshop.net.request.GetDayMerListRequest;
import com.dg11185.nearshop.net.response.GetDayMerListResponse;
import com.dg11185.nearshop.view.adapter.V_ShopListAdapter;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnPullEventListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.wlper.lib.sys.Screen;
import com.wlper.lib.uitls.LogUtils;
import com.wlper.lib.uitls.TimeUtils;
import com.wlper.lib.uitls.ViewUtils;
import com.wlper.lib.view.loading.BaseLoadLayout;
import com.wlper.lib.view.loading.LoadLayoutWithFrameAnim;

/**
 * 特惠日商家子界面。考虑到效率问题，不采用手势滑动页面的设计。
 * 
 * @author wanliang527
 * @date 2014-7-4
 * 
 */
public class AllDayShopsActivity extends SubPageActivity {
    private final static String DG_AREA_NUM = "0001900017";
    private final static int PAGE_SIZE = 5;

    private RadioGroup mRadioGroup;// 星期切换
    private LoadLayoutWithFrameAnim mLoadingView;
    private PullToRefreshListView mRefreshView;
    private ListView mShopListView;
    private SparseArray<PageExtra> mPageExtras;

    private long lastRefreshTime = -1;
    private Handler mHandler = new Handler();
    private Runnable refreshComplete = new Runnable() {
        @Override
        public void run() {
            mRefreshView.onRefreshComplete();
        }
    };
    private OnCheckedChangeListener checkedListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            clearAdapterData();
            mPageExtras.get(convertToWeek(checkedId)).reset();
            onGetDayShopList(convertToWeek(checkedId));
        }
    };

    private PullToRefreshBase.OnRefreshListener2<ListView> pullListener = new PullToRefreshBase.OnRefreshListener2<ListView>() {

        @Override
        public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            if (NetWorkUtils.isNetConnected()) {
                lastRefreshTime = System.currentTimeMillis();
                mPreferences
                        .edit()
                        .putLong(Constants.HOME_P_REFRESH_TIME, lastRefreshTime)
                        .commit();
                mRefreshView.getLoadingLayoutProxy(true, false)
                        .setLastUpdatedLabel(
                                TimeUtils.computeTimeInterval(lastRefreshTime)
                                        + "更新过");
                CacheConstant.deleteCacheFolder(Constants.getDayMerList);
                clearAdapterData();
                int week = convertToWeek(mRadioGroup.getCheckedRadioButtonId());
                mPageExtras.get(week).reset();
                onGetDayShopList(week);
            } else {
                mHandler.postDelayed(refreshComplete, 2000);
                ViewUtils.showToast(mActivity, R.string.cant_connect_network);
            }
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            onGetDayShopList(convertToWeek(mRadioGroup
                    .getCheckedRadioButtonId()));
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_day_shops2);
        mPageExtras = new SparseArray<AllDayShopsActivity.PageExtra>();
        for (int i = 0; i < 7; i++) {
            PageExtra extra = new PageExtra();
            mPageExtras.put(i, extra);
        }
        lastRefreshTime = mPreferences.getLong(Constants.HOME_P_REFRESH_TIME,
                -1);
        initView();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        mRadioGroup = (RadioGroup) findViewById(R.id.ra_group);
        mRadioGroup.setOnCheckedChangeListener(checkedListener);
        initLoadingView();
        initRefreshView();
        setSubPageTitle("特惠日优惠");
        ((RadioButton) findViewById(convertCheckedId())).setChecked(true);
    }

    private void initLoadingView() {
        mLoadingView = (LoadLayoutWithFrameAnim) findViewById(R.id.loading_view);
        mLoadingView.setStateHandler(new BaseLoadLayout.LoadStateHandler() {

            @Override
            public void onReload() {
                onGetDayShopList(convertToWeek(mRadioGroup
                        .getCheckedRadioButtonId()));
            }

            @Override
            public void onLoading() {
            }

            @Override
            public void onLoadSuccess() {
            }

            @Override
            public void onLoadFailed() {
            }
        });
    }

    private void initRefreshView() {
        mRefreshView = (PullToRefreshListView) findViewById(R.id.refresh_view);
        mShopListView = mRefreshView.getRefreshableView();
        mShopListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // 点击会员日商家的事件处理
                V_ShopListAdapter.ViewHolder viewHolder = (V_ShopListAdapter.ViewHolder) view
                        .getTag();
                Intent intent = new Intent(mActivity, ShopDetailActivity.class);
                intent.putExtra("merchant_id", viewHolder.merchantId);
                startActivity(intent);
            }
        });
        mRefreshView.setOnRefreshListener(pullListener);
        mRefreshView.setPullToRefreshOverScrollEnabled(false);
        mRefreshView.getRefreshableView().setVerticalScrollBarEnabled(false);// 隐藏滚动条
        Screen screen = Screen.getInstance(mActivity);
        mRefreshView.setMinimumHeight(screen.getScreenHeight());
        final Drawable headDrawable = getResources().getDrawable(
                R.drawable.wl_anim_header_loading);
        mRefreshView
                .setOnPullEventListener(new OnPullEventListener<ListView>() {

                    @Override
                    public void onPullEvent(
                            PullToRefreshBase<ListView> refreshView,
                            State state, Mode direction) {
                        if (State.PULL_TO_REFRESH == state) {
                            ((AnimationDrawable) headDrawable).start();
                            if (lastRefreshTime != -1) {
                                mRefreshView
                                        .getLoadingLayoutProxy(true, false)
                                        .setLastUpdatedLabel(
                                                TimeUtils
                                                        .computeTimeInterval(lastRefreshTime)
                                                        + "更新过");
                            }
                        } else if (State.RESET == state) {
                            ((AnimationDrawable) headDrawable).stop();
                        }

                    }
                });
        // 获取头部下拉区域
        ILoadingLayout headerLayout = mRefreshView.getLoadingLayoutProxy(true,
                false);
        headerLayout.setTextTypeface(Typeface.SERIF);
        headerLayout.setLoadingDrawable(headDrawable);
        headerLayout.setPullLabel(getResources().getString(
                R.string.xlistview_header_hint_normal));
        headerLayout.setReleaseLabel(getResources().getString(
                R.string.xlistview_header_hint_ready));
        headerLayout.setRefreshingLabel(getResources().getString(
                R.string.xlistview_header_hint_refresh));
        if (lastRefreshTime != -1) {
            headerLayout.setLastUpdatedLabel(TimeUtils
                    .computeTimeInterval(lastRefreshTime) + "更新过");
        }
        FrameLayout hInnerLayout = mRefreshView.getHeaderLayout()
                .getInnerLayout();
        int left = hInnerLayout.getPaddingLeft();
        int right = hInnerLayout.getPaddingRight();
        int top = hInnerLayout.getPaddingTop();
        hInnerLayout.setPadding(left, top, right, 0);

        ILoadingLayout footerLayout = mRefreshView.getLoadingLayoutProxy(false,
                true);
        footerLayout.setLoadingDrawable(getResources().getDrawable(
                R.drawable.wl_ic_loading));
        footerLayout.setPullLabel(getResources().getString(
                R.string.xlistview_footer_hint_normal));
        footerLayout.setReleaseLabel(getResources().getString(
                R.string.xlistview_header_hint_ready));
        footerLayout.setRefreshingLabel(getResources().getString(
                R.string.xlistview_footer_hint_loading));
        footerLayout.setTextTypeface(Typeface.SERIF);
    }

    /**
     * 发起获取特惠日商家的网络连接
     * 
     * @param week
     */
    private void onGetDayShopList(final int week) {
        if (week < 0 || week > 6 || getPageExtra(week) == null) {
            mHandler.post(refreshComplete);
            return;
        }
        final PageExtra extra = getPageExtra(week);
        if (extra.counts > -1 && extra.index >= extra.counts) {
            mHandler.post(refreshComplete);
            ViewUtils.showToast(mActivity, R.string.no_data_anymore);
            return;
        }
        final boolean isFirst = extra.counts == -1 ? true : false;
        if (isFirst) {
            mHandler.post(refreshComplete);
            mLoadingView.onLoading();
        }
        GetDayMerListRequest req = new GetDayMerListRequest();
        req.add(GetDayMerListRequest.AREA_NUM, DG_AREA_NUM);
        req.add(GetDayMerListRequest.PAGE_NUM, ++extra.page + "");
        req.add(GetDayMerListRequest.PAGE_SIZE, PAGE_SIZE + "");
        req.add(GetDayMerListRequest.WEEK, week + "");
        req.encryption();
        req.setActionListener(new ActionListener<GetDayMerListResponse>() {
            @Override
            public void onSuccess(GetDayMerListResponse result) {
                LogUtils.logNetReturn(Constants.getDayMerList,
                        result.responseStr);
                mHandler.post(refreshComplete);
                if (result.statusStr.equals("SUCCESS")) {
                    mLoadingView.onLoadSuccess();
                    updateShopList(week, result);
                } else {
                    LogUtils.logNetError("获取会员日商家失败---" + result.statusStr);
                    onFailed(week);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                mHandler.post(refreshComplete);
                LogUtils.logNetError("获取会员日商家失败---" + resultCode);
                onFailed(resultCode, week);
            }

        });
        NetCacheClient.httpCacheGet(req);

    }

    /**
     * 获取成功，返回状态为SUCCESS后，更新商家列表
     * 
     * @param week
     * @param result
     */
    private void updateShopList(int week, GetDayMerListResponse result) {
        PageExtra extra = mPageExtras.get(week);
        boolean isFirst = extra.counts == -1 ? true : false;
        if (extra.counts < 0)
            extra.counts = Integer.valueOf(result.total);
        int retCounts = result.dayMerList.size();
        if (retCounts == 0) {
            if (isFirst) {
                mLoadingView.onNoData();
            } else {
                ViewUtils.showToast(mActivity, R.string.no_data_anymore);
            }
            return;
        }
        extra.index = extra.index + retCounts;

        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < retCounts; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("coverUrl", result.dayMerList.get(i).midPhotoUrl);
            map.put("name", result.dayMerList.get(i).merchantName);
            map.put("disContent", result.dayMerList.get(i).preferential);
            map.put("discount", HomeFragment2.getDiscountType(result.dayMerList
                    .get(i).preferentialType));
            map.put("merchantId", result.dayMerList.get(i).merchantId);
            data.add(map);
        }

        ListAdapter adapter = mShopListView.getAdapter();
        if (adapter == null) {
            adapter = new V_ShopListAdapter(mActivity, data);
            mShopListView.setAdapter(adapter);
        } else {
            V_ShopListAdapter adapter2 = null;
            if (adapter instanceof HeaderViewListAdapter) {
                adapter2 = (V_ShopListAdapter) ((HeaderViewListAdapter) adapter)
                        .getWrappedAdapter();
            } else {
                adapter2 = (V_ShopListAdapter) adapter;
            }
            adapter2.getData().addAll(data);
            adapter2.notifyDataSetChanged();
        }
    }

    /**
     * 获取失败的处理
     * 
     * @param week
     */
    private void onFailed(int week) {
        ViewUtils.showToast(mActivity, R.string.network_error);
        PageExtra extra = mPageExtras.get(week);
        boolean isFirst = extra.counts == -1 ? true : false;
        if (isFirst)
            mLoadingView.onLoadFailed();
    }

    private void onFailed(int resultCode, int week) {
        if (resultCode == NetClient.NET_DISCONNECT_CODE) {
            ViewUtils.showToast(mActivity, R.string.cant_connect_network);
        } else {
            ViewUtils.showToast(mActivity, R.string.network_error);
        }
        PageExtra extra = mPageExtras.get(week);
        boolean isFirst = extra.counts == -1 ? true : false;
        if (isFirst)
            mLoadingView.onLoadFailed();
    }

    /**
     * 获取当前RadioGroup的checkedId，转换成week代号，例如星期日为0，星期一为1.... 获取失败返回-1
     * 
     * @param radioButtonId
     * @return
     */
    private int convertToWeek(int radioButtonId) {
        switch (radioButtonId) {
            case R.id.ra_btn_mon:
                return 1;
            case R.id.ra_btn_tues:
                return 2;
            case R.id.ra_btn_wed:
                return 3;
            case R.id.ra_btn_thur:
                return 4;
            case R.id.ra_btn_fri:
                return 5;
            case R.id.ra_btn_sat:
                return 6;
            case R.id.ra_btn_sun:
                return 0;
            default:
                return -1;
        }
    }

    private int convertCheckedId() {
        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8:00"));
        int i = c.get(Calendar.DAY_OF_WEEK) - 1;
        switch (i) {
            case 0:
                return R.id.ra_btn_sun;
            case 1:
                return R.id.ra_btn_mon;
            case 2:
                return R.id.ra_btn_tues;
            case 3:
                return R.id.ra_btn_wed;
            case 4:
                return R.id.ra_btn_thur;
            case 5:
                return R.id.ra_btn_fri;
            case 6:
                return R.id.ra_btn_sat;
            default:
                return -1;
        }
    }

    /**
     * 清空商家列表适配器的数据
     */
    private void clearAdapterData() {
        ListAdapter adapter = mShopListView.getAdapter();
        if (adapter instanceof V_ShopListAdapter) {
            ((V_ShopListAdapter) adapter).getData().clear();
            ((V_ShopListAdapter) adapter).notifyDataSetChanged();
        } else if (adapter instanceof HeaderViewListAdapter) {
            V_ShopListAdapter adapter2 = (V_ShopListAdapter) ((HeaderViewListAdapter) adapter)
                    .getWrappedAdapter();
            adapter2.getData().clear();
            adapter2.notifyDataSetChanged();
        }

    }

    /**
     * 获取分页加载的记录数据
     * 
     * @param week
     * @return
     */
    private PageExtra getPageExtra(int week) {
        return mPageExtras.get(week);
    }

    /**
     * 分页加载的一些额外数据。记录总数、当前加载索引值、当前加载页码
     * 
     * @author wanliang527
     * 
     */
    class PageExtra {
        private int counts = -1;
        private int index = 0;
        private int page = 0;

        void reset() {
            this.counts = -1;
            this.index = 0;
            this.page = 0;
        }

        void setCounts(int counts) {
            this.counts = counts;
        }

        void setIndex(int index) {
            this.index = index;
        }

        void setPage(int page) {
            this.page = page;
        }
    }
}
